package com.yssoft.service.core;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.yssoft.entity.core.TAccounts;
import com.yssoft.entity.core.TDepartment;
import com.yssoft.entity.core.TIndustryCategory;
import com.yssoft.entity.core.TPersonnel;
import com.yssoft.mapper.core.TDepartmentMapper;
import com.yssoft.mapper.core.TIndustryCategoryMapper;
import com.yssoft.mapper.core.TPersonnelMapper;
import com.yssoft.utils.LayuiUtil;
import com.yssoft.utils.SessionUtil;
import com.yssoft.utils.UserHelper;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
@Service
public class IndustryCategoryService
{
	@Autowired
	protected TIndustryCategoryMapper industryCategoryMapper;
	@Autowired
	protected TPersonnelMapper personnelMapper;
	@Autowired
	protected TDepartmentMapper departmentMapper;
	
	/**
	 * @方法名称: findOne
	 * @功能描述: 获取唯一行业类别数据
	 * @作者:洪丰
	 * @创建时间: 2018年4月25日 下午5:21:19
	 * @param id
	 * @return TRoles
	 */
	public TIndustryCategory queryRoleById(Integer id){
		return industryCategoryMapper.selectByPrimaryKey(id);
	}
	
	/**
	 * @方法名称: queryPage
	 * @功能描述: 分页查询列表数据
	 * @作者:洪丰
	 * @创建时间: 2018年4月25日 下午5:49:05
	 * @param page
	 * @param limit
	 * @param searchParams
	 * @return List<Map<String,Object>>
	 */
	public String queryDeptListByPropertity(){
		List<TIndustryCategory> ILists = industryCategoryMapper.selectIndustryCategoryAll();
		StringBuffer sb = new StringBuffer();
		sb.append("[");
		int i = 0;
		for (TIndustryCategory ic : ILists) {
			
			if (i != 0) {
				sb.append(",");
			}
			if (ic.getT_i_id() != null) {
				sb.append("{id:" + ic.getId() + "',pid:" + ic.getT_i_id() + "',name:" + ic.getName() + "',code:" + ic.getCode());
				if (ic.getChildrenList().size() > 0) {
					sb.append(",_children: true");
				}
				sb.append("}");
			} else {
				sb.append("{id:" + ic.getId() + "',pid:0" + "',name:" + ic.getName() + "',code:" + ic.getCode());
				if (ic.getChildrenList().size() > 0) {
					sb.append(",_children: true");
				}
				sb.append("}");
			}
			i++;
		}
		sb.append("]");
		return sb.toString();
	}
	
	/**
	 * @方法名称: addAcc
	 * @功能描述: 新增行业类别
	 * @作者:洪丰
	 * @创建时间: 2018年4月25日 下午6:20:23
	 * @param entity void
	 */
	public void addAcc(TIndustryCategory entity) {
		// 取得当前登录人
		Session session = SecurityUtils.getSubject().getSession();
		TAccounts user = (TAccounts)session.getAttribute(SessionUtil.USER_SESSION_KEY);
		TPersonnel person = personnelMapper.selectByPrimaryKey(user.gettPId());
		if(null != person){
			entity.setCreatorId(person.getId());
			entity.setCreatorName(person.getName());
		
		}
		entity.setCreateTime(new Date());
		entity.setDeleteFlag("0");
		
		industryCategoryMapper.insert(entity);
	}
	
	/**
	 * @方法名称: editAcc
	 * @功能描述: 修改行业类型
	 * @作者:洪丰
	 * @创建时间: 2018年4月25日 下午6:48:23
	 * @param entity void
	 */
	public void editAcc(TIndustryCategory entity) {
		industryCategoryMapper.updateByPrimaryKey(entity);
	}
	
	/**
	 * @方法名称: delAccById
	 * @功能描述: 逻辑删除行业类型
	 * @作者:洪丰
	 * @创建时间: 2018年4月25日 下午6:54:11
	 * @param id void
	 */
	public int delAccById(Integer id) {
		TIndustryCategory entity = new TIndustryCategory();
		entity.setId(id);
		entity.setDeleteFlag("1");
		return industryCategoryMapper.updateByPrimaryKeySelective(entity);
	}
	/**
	 * @方法名称: queryDeptListForList
	 * @功能描述: 查询行业类型List
	 * @作者:王永宁
	 * @创建时间: 2018年4月26日 下午7:54:11
	 * @param id void
	 */
	public List<TIndustryCategory> queryDeptListForList() {
		return industryCategoryMapper.selectAll();
	}
	/**
	 * @方法名称: addIndustryCategory
	 * @功能描述: 新增行业类别
	 * @作者:王永宁
	 * @创建时间: 2018年4月27日 下午6:20:23
	 * @param entity 
	 */
	public void addIndustryCategory(TIndustryCategory entity) {
		industryCategoryMapper.addIndustryCategory(entity);
	}


	/**
	 * @param tIid 
	 * @功能描述:查询行业类别树数据
	 * @作者:戈超
	 * @return
	 */
	public String queryIndustryTree() {
		//获取行业类别一级节点
		List<Map<String, Object>> node = industryCategoryMapper.queryIndustryTreeOneNode();
		/*获取行业类别全部数据*/
		List<Map<String, Object>> industryList = industryCategoryMapper.queryAllIndustry();
		for(Map<String, Object> industry : node){
			List<Map<String, Object>> children = queryIndustryTreeNode(industry.get("id").toString(), industryList);
			if(children.size() > 0){
				industry.put("children", children);
			}
		}
		//查询结果转换json
		String jsonArray = JSONObject.toJSONString(node);
		return jsonArray;
	}
	
	/**
	 * @功能描述:递归查询一级行业类别下树形数据
	 * @作者:戈超
	 * @param pId
	 * @return
	 */
	public List<Map<String, Object>> queryIndustryTreeNode(String pId, List<Map<String, Object>> industryList){
		List<Map<String, Object>> industryNode = new ArrayList<>();
		for(Map<String, Object> map : industryList){
			if(pId.equals(map.get("pId").toString())){
				List<Map<String, Object>> children = queryIndustryTreeNode(map.get("id").toString(), industryList);
				if(children.size() > 0){
					map.put("children", children);
				}
				industryNode.add(map);
			}
		}
		return industryNode;
	}
	/**
	 * @功能描述:删除行业类别
	 * @作者:王永宁
	 * @param id
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public int delIndustryCategory(String id) {
	       List<TIndustryCategory> childIndustry = industryCategoryMapper.queryIndustryChildren(id);
	        List<Integer> idList=new ArrayList<>();
	        for (TIndustryCategory industry : childIndustry) {
	            idList.add(industry.getId());
	        }
	       return  industryCategoryMapper.deleteIndustry(idList);
	}

	
    /**
     * 查询行业类别tableTree使用
     * @return
     */
	public List<Map<String,Object>> queryIndustryTableTree() {
		return industryCategoryMapper.queryAllIndustry();
	}
/**
 * 行业类别新增tree
 * @return
 */
	public List<Map<String, Object>> queryIndustryNewTree() {
        List<Map<String,Object>> industryList=null;
        industryList= industryCategoryMapper.queryAllIndustryForAdd();
        Iterator<Map<String,Object>> it = industryList.iterator();
        List<Integer> genList=new ArrayList<>();
        while (it.hasNext()) {
            Map<String, Object> map1 = it.next();
            if (map1.get("pId") == null) {
                genList.add(Integer.parseInt(map1.get("id") + ""));
                for (Map<String, Object> map2 : industryList) {
                    if (map2.get("pId")!=null && map2.get("pId").equals(map1.get("id"))) {
                        List<Map<String, Object>> childrens = (List<Map<String, Object>>) map1.get("children");
                        if (childrens == null) {
                            childrens = new ArrayList<>();
                        }
                        childrens.add(map2);
                        map1.put("children", childrens);
                    }
                }
            }else {
                for (Map<String, Object> map2 : industryList) {
                    if (map2.get("id").equals(map1.get("pId")) && map2.get("pId") != null) {
                        List<Map<String, Object>> childrens = (List<Map<String, Object>>) map2.get("children");
                        if (childrens == null) {
                            childrens = new ArrayList<>();
                        }
                        childrens.add(map1);
                        map2.put("children", childrens);
                    }
                }
            }
        }
        Iterator<Map<String,Object>> it2 = industryList.iterator();
        while (it2.hasNext()) {
            Map<String,Object> map = it2.next();
            if(map.get("pId")!=null){
                it2.remove();
            }
        }
        return industryList;
    }

}
